package commons.base.rpc;

import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class RpcProxyFactory {

	private static final Logger log = LogManager.getLogger(RpcProxyFactory.class);
	
	private String url;
	private static Map<String, Object> proxyCache = new ConcurrentHashMap<String, Object>();

	public RpcProxyFactory(String url) {
		super();
		this.url = url;
	}
	
	public <T> T getProxy(Class<T> serviceInterface){
		String interfaceName = serviceInterface.getSimpleName();
		
		if(proxyCache.containsKey(interfaceName)){
    		return serviceInterface.cast(proxyCache.get(interfaceName));
    	}
		
		try {
			Object proxy = Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class[] { serviceInterface }, new MethodInvocationHandler(url, interfaceName));
			proxyCache.put(interfaceName, proxy);
			return serviceInterface.cast(proxy);
		} catch (Exception e) {
			log.warn(e.getMessage(), e);
		}
		
		return null;
	}
}
